/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hxg.portmgr.core.oper.RemoteClient;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author hxg
 */
public class SSH2Oper extends RemoteClientOper {

    String username = "";
    String password = "";
    private static final UserInfo defaultUserInfo = new UserInfo() {

        @Override
        public String getPassphrase() {
            return null;
        }

        @Override
        public String getPassword() {
            return null;
        }

        @Override
        public boolean promptPassword(String arg0) {
            return false;
        }

        @Override
        public boolean promptPassphrase(String arg0) {
            return false;
        }

        @Override
        public boolean promptYesNo(String arg0) {
            return true;
        }

        @Override
        public void showMessage(String arg0) {
        }
    };
    Session session;
    Channel channel;

    public SSH2Oper(String ip, int port) {
        super(ip, port);
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUsername(String username) {
        this.username = username;
    }  
    
    @Override
    public void init() {
        JSch jsch = new JSch();
        try {
            session = jsch.getSession(username,ip,port);
            session.setPassword(password);
            session.setUserInfo(defaultUserInfo);
            session.connect(5000);
            channel = session.openChannel("shell");
            channel.connect(5000);
            is = channel.getInputStream();
            os = channel.getOutputStream();
            startReader();
        } catch (Exception ex) {
            Logger.getLogger(SSH2Oper.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void close() {
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
        is = null;
        os = null;
    }
}
